#ifndef __HTTPSERVER_H__
#define __HTTPSERVER_H__

#include "TcpServer.h"
#include "HttpRequest.h"
#include "HttpResponse.h"
#include "HttpRouter.h"
#include <memory>
#include <mutex>
#include <unordered_map>

class HttpServer {
public:
    using HttpHandler = HttpRouter::HttpHandler;
    using Middleware = HttpRouter::Middleware;
    
public:
    HttpServer(const std::string &ip, unsigned short port, 
               int subReactorNum = 1, int threadNum = 4, int queueSize = 1024);
    ~HttpServer();
    
    // 服务器控制
    void start();
    void stop();
    
    // 路由注册
    void get(const std::string& path, HttpHandler handler);
    void post(const std::string& path, HttpHandler handler);
    void put(const std::string& path, HttpHandler handler);
    void del(const std::string& path, HttpHandler handler);
    void options(const std::string& path, HttpHandler handler);
    void route(HttpMethod method, const std::string& path, HttpHandler handler);
    
    // 静态文件服务
    void serveStatic(const std::string& urlPrefix, const std::string& localPath);
    
    // 中间件
    void use(Middleware middleware);
    
    // 获取路由器（用于更高级的配置）
    HttpRouter& getRouter() { return _router; }

private:
    void onNewConnection(const TcpServer::TcpConnectionPtr &conn);
    void onMessage(const TcpServer::TcpConnectionPtr &conn);
    void onClose(const TcpServer::TcpConnectionPtr &conn);
    
    void handleHttpRequest(const TcpServer::TcpConnectionPtr &conn, const std::string& requestData);
    
private:
    TcpServer _tcpServer;
    HttpRouter _router;
    
    // HTTP连接状态管理
    std::unordered_map<int, std::string> _connectionBuffers; // fd -> 缓冲区
    std::mutex _buffersMutex;
};

#endif